package com.zx.article.typePay.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zx.article.typePay.dao.ITypePayDao;
import com.zx.article.typePay.model.TypePayModel;
import com.zx.article.util.DBUtils;

public class TypePayDaoImpl implements ITypePayDao {

	private DBUtils dbUtils = new DBUtils();

	@Override
	public String insertId(String name) {
		String sqlString = "INSERT INTO type_pay(type_id,type_pay.article_pay,type_pay.check_pay,type_pay.page_pay) VALUES(?,0,0,0) ";
		Object[] valObjects = { name };
		return dbUtils.update(sqlString, valObjects);
	}

	@Override
	public int getCount(TypePayModel typePayModel) {
		StringBuffer sqlBuffer = new StringBuffer("SELECT COUNT(1) FROM type_pay ");
		List<Object> appendWhere = appendWhere(sqlBuffer, typePayModel);
		return dbUtils.queryCount(sqlBuffer.toString(), appendWhere.toArray());
	}

	@Override
	public List<TypePayModel> queryList(TypePayModel typePayModel) {
		StringBuffer sqlBuffer = new StringBuffer("SELECT * FROM type_pay ");
		List<Object> appendWhere = appendWhere(sqlBuffer, typePayModel);
		return dbUtils.queryList(sqlBuffer.toString(), appendWhere.toArray(), TypePayModel.class, getMap());
	}

	private List<Object> appendWhere(StringBuffer sqlBuffer, TypePayModel typePayModel) {
		List<Object> list = new ArrayList<>();
		sqlBuffer.append("where 1=1 ");
		String typeId = typePayModel.getTypeId();
		if (typeId != null && !typeId.isEmpty()) {
			sqlBuffer.append("and type_id like ? ");
			list.add(typeId);
		}
		if (typePayModel.isPageOn()) {
			sqlBuffer.append("limit ?,? ");
			list.add(typePayModel.getRowStart());
			list.add(typePayModel.getRowCount());
		}
		return list;
	}

	private Map<String, String> getMap() {
		Map<String, String> map = new HashMap<>();
		map.put("typeId", "type_id");
		map.put("articlePay", "article_pay");
		map.put("checkPay", "check_pay");
		map.put("pagePay", "page_pay");
		return map;
	}

	@Override
	public TypePayModel queryModel(String name) {
		String sqlString = "SELECT * FROM type_pay WHERE type_pay.type_id = ? ";
		Object[] valObjects = { name };
		return dbUtils.queryOne(sqlString, valObjects, TypePayModel.class, getMap());
	}

	@Override
	public String updata(TypePayModel typePayModel) {
		String sqlString = "UPDATE type_pay SET type_pay.article_pay = ? ,type_pay.check_pay = ? ,type_pay.page_pay = ? WHERE type_pay.type_id = ? ";
		Object[] valObjects = { typePayModel.getArticlePay(), typePayModel.getCheckPay(), typePayModel.getPagePay(),
				typePayModel.getTypeId() };
		return dbUtils.update(sqlString, valObjects);
	}

}
